﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.Web.Caching;

namespace Job.Core
{
    /// <summary>
    /// 网络类
    /// </summary>
    public class NetHelper
    {
        /// <summary>
        /// 获取IP地址
        /// </summary>
        /// <returns></returns>
        public static string GetIP()
        {
            string strUserIP = System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
            if (string.IsNullOrEmpty(strUserIP))
            {
                //没有代理服务器,如果有代理服务器获取的是代理服务器的IP
                strUserIP = System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
            }
            return strUserIP;
        }

        /// <summary>
        /// 模拟CMD命令ping
        /// </summary>
        /// <param name="strDomain"></param>
        /// <returns></returns>
        public static string CMDPing(string strDomain)
        {
            string strReturn = "";

            Process p = new Process();
            //设定必要属性
            p.StartInfo.FileName = "cmd.exe";
            p.StartInfo.UseShellExecute = false;
            p.StartInfo.RedirectStandardInput = true;//介于CMD输入
            p.StartInfo.RedirectStandardOutput = true;//基于CMD输出
            p.StartInfo.RedirectStandardError = true;//
            p.StartInfo.CreateNoWindow = true;//是否创建窗口
            p.Start();//开始执行Process
            p.StandardInput.WriteLine("ping -n 1 " + strDomain);
            p.StandardInput.WriteLine("exit");
            strReturn = p.StandardOutput.ReadToEnd();

            List<string> listStr = strReturn.Split("\r\n".ToCharArray(), StringSplitOptions.RemoveEmptyEntries).ToList<string>();

            if (listStr.Count > 5)
                strReturn = listStr[4];
            else
                strReturn = "ping时出异常";

            return strReturn;
        }

        /// <summary>
        /// 防止短时间内多次访问
        /// </summary>
        /// <param name="strType">此类型+IP地址作为唯一的KEY，请确保其唯一性</param>
        /// <param name="intAllowThroughTime">在规定时间内允许通过的次数</param>
        /// <param name="intMaxSeconds">规定的最大范围时间 以秒为单位</param>
        /// <returns></returns>
        public static bool StopCrawler(string strType, int intAllowThroughTime, double intMaxSeconds)
        {
            System.Web.Caching.Cache modelCache = System.Web.HttpRuntime.Cache;
            
            string strCacheName = strType + NetHelper.GetIP();

            int hit = (Int32)(modelCache[strCacheName] ?? 0);
            if (hit >= intAllowThroughTime)
                return false;
            else
                hit++;
            //过期时间 = 可访问情况下最后一次访问时间 + 缓存预过期时间
            modelCache.Insert(strCacheName, hit, null, DateTime.Now.AddSeconds(intMaxSeconds), System.Web.Caching.Cache.NoSlidingExpiration);
            //if (hit == 1)
            //    modelCache.Insert(strCacheName, hit, null, DateTime.Now.AddSeconds(intMaxSeconds), System.Web.Caching.Cache.NoSlidingExpiration);
            //else
            //    modelCache.Insert(strCacheName, hit, null, DateTime.Now.AddMinutes(Convert.ToDouble(ConfigHelper.GetConfigValue("UnLockMinutes"))), System.Web.Caching.Cache.NoSlidingExpiration);
            return true;
        }
    }
}
